# -*- coding: utf-8 -*-
import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper
from urllib.parse import  urlencode
from threading import Thread
import execjs

class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "海保人寿大金刚A款重大疾病保险"
    # 生产产品数据
    def genProductInfo(self):
        plan = {

            "planA":{
                # 年龄
                "year": [str(i) for i in range(0, 36)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000", "400000", "500000"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费期间
                "interval": ["10", "15", "20", "30"],
                # 保险期间
                "expire": ["至70岁", "至80岁", "终身"],
                # 产品计划
                "plan": ["A款", "B款", "C款", "D款"]

            },
            "planB":{

                # 年龄
                "year": [str(i) for i in range(36, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000", "400000", "500000"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费期间
                "interval": ["10", "15", "20"],
                # 保险期间
                "expire": ["至70岁", "至80岁", "终身"],
                # 产品计划
                "plan": ["A款", "B款", "C款", "D款"]

            },
            "planC":{

                # 年龄
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000", "300000", "400000", "500000"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费期间
                "interval": ["10", "15"],
                # 保险期间
                "expire": ["至70岁", "至80岁", "终身"],
                # 产品计划
                "plan": ["A款", "B款", "C款", "D款"]

            },
            "planD":{
                # 年龄
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "200000"],
                # 缴费方式
                "payType": ["年缴"],
                # 缴费期间
                "interval": ["10"],
                # 保险期间
                "expire": ["至70岁", "至80岁", "终身"],
                # 产品计划
                "plan": ["A款", "B款", "C款", "D款"]

            }

        }
        for k in plan:
            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["payType"],plan[k]["interval"],plan[k]["expire"],plan[k]["plan"]):

                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5],v[6]
                ))
                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5],v[6]
                ))

    #执行爬虫
    def requestJson(self,dt=None,mysql=None):

        # dt = {
        #     "year":"0",
        #     "gender":"M",
        #     "money":"100000",
        #     "interval":"20",
        #     "expire":"终身",
        #     "plan":"D款"
        # }

        if dt["expire"] == "至70岁":

            expire = "70"

        elif dt["expire"] == "至80岁":

            expire = "80"

        else:

            expire = "1000"

        if dt["plan"] == "A款":

            plan = "218105"

        elif dt["plan"] == "B款":

            plan = "218104"

        elif dt["plan"] == "C款":

            plan = "218103"

        else:

            plan = "218102"


        data = {

            "userId":"",
            "add": "海南省",
            "addType": "1",
            "occupation": "教育机构 教师",
            "level": "1",
            "occupation_appntJobCode":"1201001",
            "occupation_appntJobLevel": "1",
            "birthday": "{year} - 01 - 01".format( year = str(2020-int(dt["year"]))),
            "jobCode": "1201001",
            "sex": "0" if dt["gender"] == "M" else "1",
            "age": dt["year"],
            "days": "37",
            "payIntv": "12",
            "payendyearFlag": "Y",
            "payendYear": dt["interval"],
            "insurencePeriodFlag": "A",
            "insurencePeriod": expire,
            "insuredAmount": str(int(int(dt["money"])/10000)),
            "productCode": plan,
            "productMoney": "2631.00"
        }


        payload = urlencode( data ).replace("+","")

        r = requests.post( url = domain[self.name]["url"].format( plan ),headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and len(r.text) !=0:

            data = {
                "fee":float(r.text),
                "interval":(int(int(dt["money"])/10000))
            }

            price = self.calcPreminum( data ) *10

            price = Helper.decimalParse( price )

            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            mysql.updatePrice(data)

        else:

            data = {

                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*更新产品价格失败:%d*/" % dt["id"])


    def main(self, mysql):
        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)


    def startProcess(self):
        for i in range(5):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))
            # p = Thread( target=self.test,args=(mysql,))

            t.start()

    #计算保费
    def calcPreminum(self,data=None):

        js = '''
        function accMul(num1,num2){//两个浮点数相乘，js本身的有bug
            var m=0,s1=num1.toString(),s2=num2.toString();
            try{m+=s1.split(".")[1].length}catch(e){};
            try{m+=s2.split(".")[1].length}catch(e){};
            return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
        }
        '''
        cxt = execjs.compile( js )

        price = cxt.call("accMul",data["fee"],data["interval"])

        return price

